<template>
    <div>
        <Row>
            <i-col span="20">
                <Row>
                    <Card>
                        <p slot="title">
                            <Icon type="bag"></Icon>
                            添加商品
                        </p>
                        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">

                            <FormItem label="商品名称" prop="name">
                                <Input v-model="formValidate.name" placeholder="请输入服务名称"></Input>
                            </FormItem>
                            <FormItem label="缩略图" prop="thumb">
                                <Upload ref="avatar_upload" :before-upload="beforeUpload"
                                        :show-upload-list="showProgress"
                                        type="drag"
                                        :on-success="uploadAvatarSuccess"
                                        :action="`${host}/admin/upload?token=${$store.state.access_token}`">
                                    <div style="padding: 20px 0">
                                        <img style="width: 80%;height: auto" v-if="formValidate.thumb" :src="formValidate.thumb"/>
                                        <template v-if="!formValidate.thumb">
                                            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                            <p>点击或将文件拖拽到这里上传</p>
                                        </template>
                                    </div>
                                </Upload>

                            </FormItem>
                            <FormItem label="商品分类" prop="category">
                                <Cascader :data="categories" v-model="formValidate.category"  filterable></Cascader>

                            </FormItem>
                            <FormItem label="简介" prop="description">
                                <Input v-model="formValidate.description" type="textarea" placeholder="请输入简介"></Input>
                            </FormItem>
                            <FormItem label="商品价格" prop="price">
                                <Input v-model="formValidate.price" icon="social-yen" placeholder="请输入商品价格"></Input>
                            </FormItem>
                            <FormItem label="运费" prop="ship_money">
                                <Input v-model="formValidate.ship_money" icon="social-yen" placeholder="请输入商品价格"></Input>
                            </FormItem>
                            <FormItem label="销量" prop="sell_num">
                                <InputNumber :min="0" v-model="formValidate.sell_num"></InputNumber>
                            </FormItem>
                            <FormItem label="相册" prop="photos">
                                <div class="upload-list" v-for="item in uploadList">
                                    <template v-if="item.status === 'finished'">
                                        <img :src="item.url">
                                        <div class="upload-list-cover">
                                            <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                                            <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                                    </template>
                                </div>
                                <Upload
                                        ref="upload"
                                        :show-upload-list="false"
                                        :on-success="handleSuccess"
                                        :format="['jpg','jpeg','png']"
                                        :max-size="2048"
                                        :on-format-error="handleFormatError"
                                        :on-exceeded-size="handleMaxSize"
                                        :before-upload="handleBeforeUpload"
                                        multiple
                                        type="drag"
                                        :action="`${host}/admin/upload?token=${$store.state.access_token}\``"
                                        style="display: inline-block;width:58px;">
                                    <div style="width: 58px;height:58px;line-height: 58px;">
                                        <Icon type="camera" size="20"></Icon>
                                    </div>
                                </Upload>
                                <Modal title="查看图片" v-model="visible">
                                    <img :src="show_url" v-if="visible" style="width: 100%">
                                </Modal>
                            </FormItem>
                            <FormItem label="状态">
                                <i-switch v-model="formValidate.status" size="large">
                                    <span slot="open">启用</span>
                                    <span slot="close">禁用</span>
                                </i-switch>
                            </FormItem>

                            <FormItem label="图文详情">
                                <div>
                                    <w-editor :content.sync="formValidate.content"></w-editor>
                                </div>
                            </FormItem>
                            <FormItem>
                                <Button :loading="$store.state.loading" type="primary"
                                        @click="handleSubmit('formValidate')">提交
                                </Button>
                                <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置
                                </Button>
                            </FormItem>
                        </Form>
                    </Card>
                </Row>
            </i-col>
        </Row>
    </div>
</template>
<script type="text/jsx">

  import url from '../../../config/url'
  import time from '../../../libs/time'

  import E from 'wangeditor'
  import util from '../../../libs/util'
  import WEditor from '../../common/components/Weditor.vue'

  export default {

    components: {
      WEditor,
    },
    name: 'shop-good-add',

    data () {
      return {
        uploadList:[],

        visible: false,
        host: url.host,
        categories: [],
        show_url:'',
        formValidate: {
          name: '',
          category: [],
          thumb: '',
          price: '',
          ship_money:'',
          sell_num:0,
          description: '',
          status: true,
          content: '',
          photos:[]
        },
        showProgress: false,
        ruleValidate: {
          name: [
            {required: true, message: '服务名不能为空', trigger: 'blur'}
          ],
          thumb: [
            {required: true, message: '请上传缩略图', trigger: 'blur'}
          ],
          category:[
            { required: true, type: 'array', min: 1, message: '请选择分类', trigger: 'change' },
          ],
          description: [
            {required: true, message: '简介不能为空', trigger: 'blur'},
            {min: 5, message: '简介最少需要5个字', trigger: 'blur'},
            {max: 30, message: '简介最多只你能30个字', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '预估价格不能为空', trigger: 'blur'},
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '价格不正确',
              trigger: 'blur'
            }
          ],
          ship_money:[
            {required: true, message: '预估价格不能为空', trigger: 'blur'},
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '价格不正确',
              trigger: 'blur'
            }
          ],
        }

      }
    },
    computed: {},

    mounted () {
      this.loadMenus()
//      this.loadServices()
    },
    destroyed () {

    },
    methods: {
      loadMenus () {
        $api.get(url.shop_category_menus).then((res) => {
          if (res.status) {
            this.categories = []
            res.data.map((item) => {
              let menu_item = {value: item.id, label: item.name}
              let menu_child = []
              item.child.map((child) => {
                let child_item = {value: child.id, label: child.name}
                menu_child.push(child_item)
              })
              menu_item.children = menu_child
              this.categories.push(menu_item)
            })
          }
        })
      },

      beforeUpload () {
        this.showProgress = true
        return true
      },

      handleView (url) {
        this.show_url = url;
        this.visible = true;
      },
      handleRemove (file) {
        // 从 upload 实例删除数据
        this.uploadList.splice(this.uploadList.indexOf(file), 1);
        this.formValidate.photos.splice(this.formValidate.photos.indexOf(file.url),1)
      },
      handleSuccess (res, file) {
        // 因为上传过程为实例，这里模拟添加 url
        file.url = res.data.url;
        this.formValidate.photos.push(res.data.url)
        this.uploadList.push(file)
        console.log(res)
      },
      handleFormatError (file) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '文件格式不正确，请上传 jpg 或 png 格式的图片。'
        });
      },
      handleMaxSize (file) {
        this.$Notice.warning({
          title: '超出文件大小限制',
          desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
        });
      },
      handleBeforeUpload () {
        const check = this.uploadList.length < 5;
        if (!check) {
          this.$Notice.warning({
            title: '最多只能上传 5 张图片。'
          });
        }
        return check;
      },

      uploadAvatarSuccess (response, file, fileList) {
        this.showProgress = false
        console.log(response.data)
        this.$refs.avatar_upload.clearFiles()
        if (response.status) {
          this.formValidate.thumb = response.data.url
        }

      },
      handleSubmit (name) {

          this.$refs[name].validate((valid) => {
            if (valid) {
              let data = this.formValidate
              data.category = data.category[data.category.length - 1]
              this.$store.commit('setLoading', {loading: true})
              data.status = data.status ? 1 : 0
              $api.post(url.shop_good, data).then((res) => {
                this.$store.commit('setLoading', {loading: false})
                if (res.status) {
                  this.$Message.success('添加成功')
                  util.closeCurrentPage(this,'service_add')
                }
              })
            } else {
              this.$Message.error('表单验证失败!')
            }
          })


      },
      handleReset (name) {
        this.$refs[name].resetFields()

      }

    }
  }
</script>
<style lang="less" scoped>
    .fitter-panel {
        background: #f0f0f0;
        padding: 12px;
        display: flex;
        flex-direction: row;
        align-items: center;
        p {
            font-size: 12px;
            margin-left: 12px;
            margin-right: 12px;
        }
    }
    .thumb {
        max-height: 120px;
        max-width: 100%;
    }

    .button-group-panel {
        margin-top: 12px;
    }

    .table-content {
        margin-top: 12px;
    }
    .upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .upload-list img{
        width: 100%;
        height: 100%;
    }
    .upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .upload-list:hover .upload-list-cover{
        display: block;
    }
    .upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>